package com.zbp.config.taskExecutor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

@Slf4j
@Service
public class AsyncTaskService {

    @Async
    public void executeAsyncTask(int i) {
        System.out.println("线程" + Thread.currentThread().getName() + " 执行异步任务：" + i);
    }

    @Async
    public Future<Object> subByAsync(int time) throws Exception {
        System.out.println("线程" + Thread.currentThread().getName() + " 执行异步任务");
        long start = System.currentTimeMillis();
        Thread.sleep(200L);
        long end = System.currentTimeMillis();
        return new AsyncResult<>(end - start);
    }

    @Async
    public Future<Map> returnSubByAsync(List<Future<Object>> futureList) {
        long start = System.currentTimeMillis();
        Map<Integer, Object> returnMap = new HashMap<>();
        while (true) {
            if (returnMap.size() == futureList.size()) {
                break;
            }
            for (int i = 0; i < futureList.size(); i++) {
                if (!returnMap.containsKey(i)) {
                    Future<Object> objectFuture = futureList.get(i);
                    if (objectFuture.isDone()) {
                        try {
                            returnMap.put(i, objectFuture.get());
                        } catch (Exception e) {
                            returnMap.put(i, e.getMessage());
                        }
                    }
                }
            }
        }
        long end = System.currentTimeMillis();
        log.info("线程" + Thread.currentThread().getName() + " 获取执行结果时间：" + (end - start));
        return new AsyncResult<>(returnMap);
    }
}

